import { createVuePlugin } from 'vite-plugin-vue2'
import ViteCommonjs from 'vite-plugin-commonjs';
import viewHtmlPlugin from './scripts/vite-plugins/view.js';
import mockPlugin from './scripts/vite-plugins/mock.js'
import path from 'path';
import { defineConfig, loadEnv } from "vite"
import { createProxyConfig } from './config/viteProxy.js'; // <-- 导入新的代理配置函数

const PROT = 5003

/** @type {import('vite').UserConfig} */
export default defineConfig(({ mode }) => {
    const env = loadEnv(mode, process.cwd(), '')
    const { HOST, AGENCY_TOKEN_NAME } = env

    // 直接调用函数生成代理配置
    const proxy = createProxyConfig(env);
    
    return  {
        define: {
            process: {
                env: {
                    MY_BUILD_MODE: "production",
                }
            },
            // 确保全局变量在开发环境中可用
            global: 'globalThis',
            $: 'window.$',
            jQuery: 'window.jQuery',
            HT: 'window.HT',
            // 为 CommonJS 模块提供 exports 和 module 对象
            exports: '{}',
            module: '{ exports: {} }'
        },
        test: {},
        root: './',
        server: {
            host: HOST,
            fs: {
                allow: ['..']
            },
            port: PROT,
            proxy, // <-- 直接使用生成的配置
        },
        plugins: [
            ViteCommonjs({
                // 确保处理所有包含 exports 的文件
                include: [
                    /node_modules/,
                    /\.vue$/,
                    /\.js$/
                ],
                // 显式转换 CommonJS 语法
                transformMixedEsModules: true
            }),
            createVuePlugin(),
            viewHtmlPlugin(AGENCY_TOKEN_NAME),
            mockPlugin,
        ],
        resolve: {
            extensions: ['.vue', '.js'],
            alias: {
                '@commonComponents': path.resolve(__dirname, './english-view/src/views/_components/'),
                "@bingostoreBase": path.resolve(__dirname, './english-view/src/views/bingostore/base/'),
                "@common": path.resolve(__dirname, './english-view/src/views/_common/'),
                "@base":  path.resolve(__dirname, './english-view/src/base/'),
                '@utils': path.resolve(__dirname, './english-view/src/base/utils'),
                '@bingostore': path.resolve(__dirname, './english-view/src/views/bingostore'),
                '@formKit': path.resolve(__dirname, './english-view/src/base/components/form-kit'),
            },
        },
    }
})